/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* _buildTree(vector<int>& postorder, int& rootsignal, int front, vector<int>& inorder, int back)
    {
        if (front > back || rootsignal < 0)
            return nullptr;
        TreeNode* root = new TreeNode(postorder[rootsignal]);
        int rooti = front;
        while (rooti <= back)
        {
            if (postorder[rootsignal] == inorder[rooti])
                break;
            else
                rooti++;
        }
        rootsignal--;
        root->right = _buildTree(postorder, rootsignal, rooti + 1, inorder, back);
        root->left = _buildTree(postorder, rootsignal, front, inorder, rooti - 1);

        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int i = postorder.size() - 1;
        TreeNode* root = _buildTree(postorder, i, 0, inorder, inorder.size() - 1);
        return root;
    }
};